#include <iostream>
using namespace std;
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

/*全局变量*/
int g_ticket = 10;
/*线程函数*/
void *thread_func1(void *arg)
{
    int val1 = *(int *)arg;
    int cnt = 100;
    /*设置线程分离*/
    pthread_detach(pthread_self());
    /*消耗*/
    // g_milk -= 1;
    while (g_ticket > 0)
    {
        usleep(1500);
        g_ticket--;
        printf("i am new thread1, threadId:%ld ,val1=%d, g_ticket=%d\n", pthread_self(), val1, g_ticket);
    }
    /*线程退出*/
    pthread_exit(NULL);
}

void *thread_func2(void *arg)
{
    usleep(1000);
    int cnt = 100;
    /*设置线程分离*/
    pthread_detach(pthread_self());
    while (g_ticket > 0)
    {
        g_ticket--;
        printf("i am new thread2, threadId:%ld, g_money=%d\n", pthread_self(), g_ticket);
    }
    /*线程退出*/
    pthread_exit(NULL);
}

void *thread_func3(void *arg)
{
    int cnt = 100;
    /*设置线程分离*/
    pthread_detach(pthread_self());
    while (g_ticket > 0)
    {
        usleep(1200);
        g_ticket--;
        printf("i am new thread3, threadId:%ld, g_money=%d\n", pthread_self(), g_ticket);
    }
    /*线程退出*/
    pthread_exit(NULL);
}

int main()
{
    // /*进程号*/
    // pid_t pid = getpid();

    // /*线程号*/
    // pthread_t tid = pthread_self();

    // cout << "pid:" << pid << endl;
    // cout << "tid:" << tid << endl;

    // int cnt = 100;
    // while (cnt--)
    // {
    //     sleep(1);
    // }

    /*创建线程*/
    pthread_t tid1;
    int val1 = 100;
    int ret1 = pthread_create(&tid1, NULL, thread_func1, (void *)&val1);
    if (ret1 != 0)
    {
        perror("thread create error:");
        _exit(-1);
    }
    printf("tid1=%ld\n", tid1);

    pthread_t tid2;
    int val2 = 200;
    int ret2 = pthread_create(&tid2, NULL, thread_func2, (void *)&val2);
    if (ret2 != 0)
    {
        perror("thread create error:");
        _exit(-1);
    }
    printf("tid2=%ld\n", tid2);

    pthread_t tid3;
    int val3 = 300;
    int ret3 = pthread_create(&tid3, NULL, thread_func3, (void *)&val3);
    if (ret3 != 0)
    {
        perror("thread create error:");
        _exit(-1);
    }
    printf("tid3=%ld\n", tid3);

    /*阻塞回收线程*/
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    // printf("i am thread...\n");

    int cnt = 5;
    while (cnt)
    {
        printf("i am main thread\n");
        sleep(1);
    }

    return 0;
}
